<?php
/**
 * 设备管理控制器
 */
namespace App\HttpController\Api\Admin\Device;

use App\HttpController\Api\Admin\AdminBase;
use App\HttpController\Jvt\Base;
use App\Lib\Utils;
use EasySwoole\Component\Di;
use App\Lib\Redis\Redis;
use EasySwoole\Http\Message\Status;
use EasySwoole\FastCache\Cache;

use App\Model\Device\DeviceModel as DeviceModel;
use App\Model\Device\Group as GroupModel;
use App\Model\Device\DeviceInfoModel as InfoModel;
use App\Model\Device\DeviceType as DeviceTypeModel;

use App\Model\Admin\AdminModel as UserModel;
use App\Model\Admin\Company as CompanyModel;

use App\Model\Face\Face as FaceModel;
use App\Model\Face\UpdateFace as UpdateFaceModel;

use App\HttpController\FormatSubData;
use App\Lib\Curl;

class Device extends AdminBase
{

    /**
     * 获取设备列表
     */
    public function index()
    {
        $condition = [];
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $condition['id'] = intval($this->params['id']);
        }

        if (isset($this->params['name']) && !empty($this->params['name'])) {
            $condition['name'] = ['%'.$this->params['name'].'%','like'];
        }

        if (isset($this->params['device_id']) && !empty($this->params['device_id'])) {
            $condition['device_id'] = $this->params['device_id'];
        }

        if (isset($this->params['group_id']) && !empty($this->params['group_id'])) {
            $condition['group_id'] = intval($this->params['group_id']);
        }

        $condition['school_code'] = intval($this->userinfo['school_code']);
        try {
            $deviceObj = new DeviceModel();
            $columns = '*';
            $data = $deviceObj->getDeviceData($columns, $condition,  $this->params['page'], $this->params['limit']);

            $groupObj = new GroupModel();
            $group = $groupObj->getIDName(['school_code' => $this->userinfo['school_code']]);

        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->errorJson("Server Error");
        }

        if (!empty($data['lists'])) {
            foreach ($data['lists'] as &$list) {
                $list['create_time'] = date("Y-m-d H:i:s", $list['create_time']);
                $list['groupname'] = $group[$list['group_id']] ?? '-';
                $list['username'] = $list['deviceuser'];
                $list['password'] = $list['devicepwd'];
                if ((time() - $list['last_login_time']) <= 120) {
                    $list['online'] = 1;
                } else {
                    $list['online'] = 0;
                }
            }
        }

        return $this->writeJson(200, ['data' => $data['lists'], 'count' => $data['count']]);
    }

    /**
     * 获取设备组列表
     */
    public function group()
    {
        $condition = [];
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $condition['id'] = intval($this->params['id']);
        }

        $condition['school_code'] = $this->userinfo['school_code'];

        try {
            $columns = 'id, name, sort, mark';
            $groupObj = new GroupModel();
            $data = $groupObj->getAll($columns, $condition, ['sort', 'asc']);

        } catch (\Exception $e) {
            return $this->errorJson("Server Error");
        }

        return $this->dataJson(['data' => $data]);
    }

    /**
     * 编辑设备组
     */
    public function editGroup()
    {
        $str = $this->raw;
        $this->params = json_decode(Utils::characet($str), true);

        $data['name'] = $this->params['name'];
        $data['sort'] = $this->params['sort'];
        $data['note'] = $this->params['note'];

        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            $id = 0;
        }

        try {
            $where['name'] = $data['name'];
            $where['school_code'] = $this->userinfo['school_code'];

            $res = GroupModel::create()->get($where);

            if ($res && $res['id'] != $id) {
                return $this->toJson(Status::CODE_CREATED, [], '设备组名称已存在');
            }

            if ($id > 0) {
                $model = GroupModel::create()->get($id);
            }
            if (empty($model)) {
                $data['pid'] = 0;
                $data['mark'] = 1;
                $data['create_id'] = $this->userinfo['user_id'];
                $data['create_time'] = time();
                $data['school_code'] = $this->userinfo['school_code'];
                $result = GroupModel::create($data)->save();
            } else {
                $data['update_id'] = $this->userinfo['user_id'];
                $data['update_time'] = time();
                $result = $model->update($data, ['id' => $id, 'school_code' => $this->userinfo['school_code']]);
            }
        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "Server Error");
        }

        if ($result) {
            return $this->toJson(0, ['id' => $result], '操作成功');
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, ['id' => 0 ], '操作失败');
        }
    }

    /**
     * 删除设备组
     */
    public function delGroup()
    {
        $id = $this->params['id'];
        try {
            $groupObj = new GroupModel();
            $result = $groupObj->destroy($id);
        } catch(\Exception $e) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "Server Error");
        }

        if ($result) {
            return $this->toJson(0, [], '删除成功');
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '删除失败');
        }
    }

    /**
     * 添加与修改设备
     */
    public function store()
    {
        $str = $this->raw;
        $this->params = json_decode(Utils::characet($str), true);

        if (isset($this->params['id']) && $this->params['id'] > 0) {
            $this->edit();
        } else {
            $this->add();
        }
    }

    /**
     * 添加设备
     */
    private function add()
    {
        $str = $this->raw;
        $this->params = json_decode(Utils::characet($str), true);

        $data = [];
        $info = [];
        $data['name'] = $this->params['name'];

        if (isset($this->params['device_id']) && !empty($this->params['device_id'])){
            $data['device_id'] = trim($this->params['device_id']);
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备序列号');
        }

        if (isset($this->params['sort']) && !empty($this->params['sort'])) {
            $data['sort'] = $this->params['sort'];
        } else {
            $data['sort'] = 1;
        }

        if (isset($this->params['funtype']) && !empty($this->params['funtype'])) {
            $data['funtype'] = $this->params['funtype'];
        } else {
            $data['funtype'] = 1;
        }

        $info['remark'] = $this->params['remark'];
        $info['positions'] = $this->params['positions'];

        //$baseINI = \Yaconf::get('basebt');
        $baseINI = $this->getConfig('basebt');

        if ($baseINI['type'] == 'cloud') {
            if (isset($this->params['device_uuid']) && !empty($this->params['device_uuid'])){
                $data['device_uuid'] = trim($this->params['device_uuid']);
            } else {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备UUID');
            }
        } else {
            if (isset($this->params['ip']) && !empty($this->params['ip'])) {
                $data['ip'] = $this->params['ip'];
            } else {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备IP地址');
            }
        }

        if (isset($this->params['deviceuser']) && !empty($this->params['deviceuser'])) {
            $info['deviceuser'] = trim($this->params['deviceuser']);
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备账号');
        }

        if (isset($this->params['devicepwd']) && !empty($this->params['devicepwd'])) {
            $info['devicepwd'] = trim($this->params['devicepwd']);
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备密码');
        }

        try {
            $deviceObj = new DeviceModel();
            $infoObj = new InfoModel();

            // 查询当前公司添加了多少个设备，是否超过公司限定
            /*$count = $deviceObj->getCount('id', ['school_code' => $this->userinfo['school_code']]);

            $companyObj = new CompanyModel();
            $company = $companyObj->getOne('id,devicenum', ['id' => $this->userinfo['school_code']]);
            if ($count >= $company['devicenum']) {
                return $this->toJson(Status::CODE_CREATED, '公司总设备数已达到'.$company['devicenum'].'个', []);
            }*/

            $where = [];
            $where['name'] = $data['name'];

            // 修改，则剔除当前用户的名称
            $where['school_code'] = $this->userinfo['school_code'];
            $isset = $deviceObj->getOne('id', $where);

            if (is_array($isset) && !empty($isset)) {
                return $this->toJson(Status::CODE_CREATED, [], '设备名称已存在');
            }

            if ($baseINI['type'] == 'cloud') {
                $uuWhere = [];
                $uuWhere['device_uuid'] = $data['device_uuid'];
                $uuWhere['school_code'] = $this->userinfo['school_code'];

                $isset = $deviceObj->getOne('id', $uuWhere);
                if (is_array($isset) && !empty($isset)) {
                    return $this->toJson(Status::CODE_CREATED, [], '设备UUID已存在');
                }
            }

            $userObj = new UserModel();
            $userInfo = $userObj->getOne('device_user, device_pwd, username', ['id' => $this->userinfo['user_id']]);

            // 添加
            $data['create_id'] = $this->userinfo['user_id'];
            $data['group_id'] = $this->params['group_id'];
            $data['school_code'] = $this->userinfo['school_code'];
            $data['device_remark'] = substr(md5(substr(md5($userInfo['username']).mt_rand(111, 999), 26).date('ymdHis', time())), 22);
            $data['create_time'] = time();
            $data['mark'] = 1;

            // 设置账号和密码
            $data['username'] = $userInfo['device_user'];
            $data['password'] = $userInfo['device_pwd'];

            $devid = $deviceObj->add($data);

            if (!empty($devid)) {
                $info['devid'] = $devid;
                $infoObj->add($info);

                $data['id'] = $devid;

                // 查询当前设备下所有通行区域的人脸，并添加下发记录
                //$this->addface($data);

                return $this->toJson(0, ['id' => $devid], '添加成功');
            } else {
                return $this->toJson(Status::CODE_BAD_REQUEST, ['id' => 0 ], '操作数据失败');
            }

        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "Server Error");
        }
    }

    /**
     * 编辑设备
     */
    private function edit()
    {
        $data = [];
        $info = [];
        $data['name'] = $this->params['name'];

        if (isset($this->params['device_id']) && !empty($this->params['device_d'])){
            $data['device_id'] = $this->params['device_id'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备序列号');
        }

        if (isset($this->params['sort']) && !empty($this->params['sort'])) {
            $data['sort'] = $this->params['sort'];
        } else {
            $data['sort'] = 1;
        }

        if (isset($this->params['funtype']) && !empty($this->params['funtype'])) {
            $data['funtype'] = $this->params['funtype'];
        } else {
            $data['funtype'] = 1;
        }

        $info['remark'] = $this->params['remark'];
        $info['positions'] = $this->params['positions'];

        //$baseINI = \Yaconf::get('basebt');
        $baseINI = $this->getConfig('basebt');

        if ($baseINI['type'] == 'cloud') {
            if (isset($this->params['device_uuid']) && !empty($this->params['device_uuid'])){
                $data['device_uuid'] = $this->params['device_uuid'];
            } else {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备UUID');
            }
        } else {
            if (isset($this->params['ip']) && !empty($this->params['ip'])) {
                $data['ip'] = $this->params['ip'];
            } else {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备IP地址');
            }
        }

        if (isset($this->params['deviceuser']) && !empty($this->params['deviceuser'])) {
            $info['deviceuser'] = $this->params['deviceuser'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备账号');
        }

        if (isset($this->params['devicepwd']) && !empty($this->params['devicepwd'])) {
            $info['devicepwd'] = $this->params['devicepwd'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请输入设备密码');
        }

        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, ['id' => 0 ], '操作数据失败');
        }

        try {
            $deviceObj = new DeviceModel();
            $infoObj = new InfoModel();

            $where = [];
            $where['name'] = $data['name'];
            $where['id'] = [$id,'<>'];
            $where['school_code'] = $this->userinfo['school_code'];

            $isset = $deviceObj->getOne('id', $where);
            if (is_array($isset) && !empty($isset)) {
                return $this->toJson(Status::CODE_CREATED, [], '设备名称已存在');
            }

            $data['update_time'] = time();
            $devid = $deviceObj->update($data, ['id'=>$id]);
            $infoObj->update($info, ['devid' => $id]);

        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "Server Error");
        }

        if (!empty($devid)) {
            return $this->toJson(0, ['id' => $devid ], '修改成功');
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, ['id' => 0 ], '操作数据失败');
        }
    }

    /**
     * 删除设备
     */
    public function delete()
    {
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '参数错误');
        }

        try {
            $deviceObj = new DeviceModel();
            $udata = $deviceObj->getOne('*', ['id'=>$id]);
            $result = $deviceObj->destroy($id);
            if ($result) {
                $infoObj = new InfoModel();
                $infoObj->destroy(['devid' => $id]);

                // 删除设备中人脸更细列表数据
                // $this->delface($udata);

                return $this->toJson(0, [], '删除成功');
            } else {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '删除失败');
            }
        } catch(\Exception $e) {
            echo $e->getMessage();
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "系统错误");
        }
    }

    /**
     * 激活设备
     */
    public function sensitize()
    {
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请求失败');
        }

        try {
            $deviceObj = new DeviceModel();
            $device = $deviceObj->getDeviceInfo('*', ['id' => $id]);

            // 查询该设备是否已经被使用
            $use_where = [];
            $use_where['device_uuid'] = $device['device_uuid'];
            $use_where['last_login_time'] = [(time()-120), '>='];
            $isUse = $deviceObj->getOne('id', $use_where);

            if ($isUse) {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备已被使用');
            }

            // 查看设备是否在线
            if ((time() - $device['last_login_time']) < 120) {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备已在线，无需激活');
            }

            $baseINI = \Yaconf::get('basebt');

            if ($baseINI['type'] == 'cloud') {
                if(!isset($device['device_uuid']) || empty($device['device_uuid'])) {
                    return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备UUID丢失');
                }
            } else {
                if (!isset($device['ip']) || empty($device['ip'])) {
                    return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备IP丢失');
                }
            }

            // 组装数据
            $formatColl = new FormatSubData();

            // 封装激活数据
            $formatData = $formatColl->format($device, 22);

            // 进行发送数据
            $curlObj = new Curl();

            if ($baseINI['type'] == 'cloud') {

                // 云端程序，走中间件
                $url = "http://127.0.0.1:8011/Request";
                $result = $curlObj->request('POST', $url, $formatData, ['UUID' => $device['device_uuid']]);
            } else {
                $url = "http://{$device['ip']}:8011/Request";
                $result = $curlObj->request('POST', $url, $formatData);
            }
            $resArr = json_decode($result,true);

            if (isset($resArr['ErrorCode']) && ($resArr['ErrorCode'] == 1)) {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '激活成功，五秒后设备上线');
            } else {
                $message = $resArr['Result'] ?? '';
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '激活失败'.$message);
            }
        } catch(\Exception $e) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], 'FAIL');
        }
    }

    /**
     * 同步时间
     */
    public function synctime()
    {
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请求失败');
        }

        try {
            $deviceObj = new DeviceModel();
            $device = $deviceObj->getDeviceInfo('*', ['id' => $id]);

            $baseINI = \Yaconf::get('basebt');
            if ($baseINI['type'] == 'cloud'){
                if (!isset($device['device_uuid']) || empty($device['device_uuid'])) {
                    return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备UUID丢失');
                }
                // 云端程序，走中间件
                $url = "http://127.0.0.1:8011/Request";
            } else {
                if (!isset($device['ip']) || empty($device['ip'])) {
                    return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备IP丢失');
                }
                $url = "http://{$device['ip']}:8011/Request";
            }

            // 组装数据
            $formatColl = new FormatSubData();

            // 封装同步时间所需数据
            $formatData = $formatColl->format($device, 12);

            // 进行发送数据
            $curlObj = new Curl();

            // 直接发送数据
            $result = $curlObj->request('POST', $url, $formatData, ['UUID' => $device['device_uuid']]);

            $resArr = json_decode($result, true);

            if (isset($resArr['Code']) && ($resArr['Code'] == 1)){
                return $this->toJson(Status::CODE_OK, [], '同步成功');
            } else {
                $message = $resArr['Message'] ?? '';
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '同步失败'.$message);
            }
        } catch(\Exception $e) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], 'FAIL');
        }
    }

    /**
     * 删除设备人脸并重新下发
     */
    public function resetface()
    {
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请求失败');
        }

        try {
            $deviceObj = new DeviceModel();
            $device = $deviceObj->getDeviceInfo('*', ['id' => $id]);

            if (!isset($device['device_uuid']) || empty($device['device_uuid'])) {
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备UUID丢失');
            }

            // 组装数据
            $formatColl = new FormatSubData();

            // 0-删除所有名单，1-删除黑名单，2-删除白名单，3-删除vip名单
            $setParams['personType'] = 2;

            // 封装同步时间所需数据
            $formatData = $formatColl->format($device, 4, $setParams);

            // 进行发送数据
            $curlObj = new Curl();
            $baseINI = \Yaconf::get('basebt');

            if ($baseINI['type'] == 'cloud') {
                // 云端程序，走中间件
                $url = "http://127.0.0.1:8011/Request";
            } else {
                $url = "http://{$device['ip']}:8011/Request";
            }

            // 直接发送数据
            $result = $curlObj->request('POST', $url, $formatData, ['UUID' => $device['device_uuid']]);

            $resArr = json_decode($result, true);

            $message = $resArr['Message'] ?? '';

            if (isset($resArr['Code']) && ($resArr['Code'] == 1)) {

                // 清空设备数据成功，删除所有的下发记录，并重新生成
                $updateObj = new UpdateFaceModel();
                $result = $updateObj->destroy(['devid' => $device['id']]);

                if ($result) {
                    // 重新添加下发记录
                    $this->addface($device);
                    return $this->toJson(0, [], '清空设备人脸数据成功，等待下发');
                } else {
                    return $this->toJson(Status::CODE_BAD_REQUEST, [], '清空平台人脸数据失败'.$message);
                }
            } else {
                if ($resArr['Code'] == '1103') {
                    return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备版本不支持：比对机至少升级至，门禁机至少升级至');
                }

                return $this->toJson(Status::CODE_BAD_REQUEST, [], '清空设备人脸数据失败'.$message);
            }

        } catch(\Exception $e) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], 'FAIL');
        }
    }

    /**
     * 开门
     */
    public function opendoor()
    {
        if (isset($this->params['id']) && !empty($this->params['id'])) {
            $id = $this->params['id'];
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], '请求失败');
        }

        try {
            $deviceObj = new DeviceModel();
            $device = $deviceObj->getDeviceInfo('*', ['id' => $id]);

            $baseINI = \Yaconf::get('basebt');
            if ($baseINI['type'] == 'cloud') {
                if (!isset($device['device_uuid']) || empty($device['device_uuid'])) {
                    return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备UUID丢失');
                }
                // 云端程序，走中间件
                $url = "http://127.0.0.1:8011/Request";
            } else {
                if (!isset($device['ip']) || empty($device['ip'])) {
                    return $this->toJson(Status::CODE_BAD_REQUEST, [], '设备IP丢失');
                }
                $url = "http://{$device['ip']}:8011/Request";
            }

            // 组装数据
            $formatColl = new FormatSubData();

            // 封装同步时间所需数据
            $formatData = $formatColl->format($device, 9);

            // 进行发送数据
            $curlObj = new Curl();

            // 直接发送数据
            $result = $curlObj->request('POST', $url, $formatData, ['UUID' => $device['device_uuid']]);

            $resArr = json_decode($result, true);

            if (isset($resArr['Code']) && ($resArr['Code'] == 1)) {
                return $this->toJson(0, [], '开门成功');
            } else {
                $message = $resArr['Message'] ?? '';
                return $this->toJson(Status::CODE_BAD_REQUEST, [], '开门失败'.$message);
            }

        } catch(\Exception $e) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], 'FAIL');
        }
    }





    /**
     * 删除设备下发的人脸
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function delface($data){
        //删除这个设备下所有的下发数据
        try{
            $groupObj = new GroupModel();
            $updateFaceObj = new UpdateFaceModel();

            $updateFace = $updateFaceObj->getAll('id',['deviceremark'=>$data['deviceremark']]);
            $ids = [];
            foreach ($updateFace as $key => $value) {
                $ids[] = $value['id'];
            }

            if(count($ids) > 0){
                $updateFaceObj->destroy($ids);
            }

        }catch(\Exception $e){
            return $this->toJson(Status::CODE_BAD_REQUEST, "Server Error");
        }
    }

    /**
     * 批量删除管理员
     * @return [type] [description]
     */
    public function delAll(){
        $ids = $this->params['ids'];

        try {
            $groupObj = new DeviceGroupModel();
            $result = $groupObj->delAll($ids);
        }catch(\Exception $e) {
            // echo $e->getMessage();
            return $this->toJson(Status::CODE_BAD_REQUEST, "Server Error");
        }

        if($result) {
            return $this->toJson(Status::CODE_OK, 'OK', []);
        } else {
            return $this->toJson(Status::CODE_BAD_REQUEST, 'FAIL', []);
        }
    }


    /**
     * 查询select框中的通行区域
     * @return [type] [description]
     */
    public function select(){
        try{
            $groupObj = new GroupModel();

            $result = $groupObj->getIDNameArr(['companyid'=>$this->userinfo['companyid']]);
            $data = [];
            foreach ($result as $key => $value) {
                $data[] = ['value'=>$value['id'],'name'=>$value['name']];
            }
        }catch(\Exception $e){
            return $this->toJson(Status::CODE_BAD_REQUEST,'Server Error');
        }

        if($data){
            return $this->toJson(Status::CODE_OK, 'OK', $data);
        }else{
            return $this->toJson(Status::CODE_BAD_REQUEST, 'FAIL', []);
        }
    }



    /**
     * 添加设备时添加人脸
     */
    public function addface($udata)
    {
        try {
            $groupObj = new GroupModel();
            $updateFaceObj = new UpdateFaceModel();

            // 查询当前分组所有的人员
            $faceObj = new FaceModel();
            $where = [];
            $where['area'] = ["%,{$udata['group_id']},%", 'LIKE'];
            $where['status'] = 1;
            $where['school_code'] = $this->userinfo['school_code'];
            $face = $faceObj->getAll('*', $where);

            if ($face) {
                $dataInsert = [];
                foreach ($face as $key => $value) {
                    if (!isset($value['imgpath']) || empty($value['imgpath'])) {
                        continue;
                    }

                    $upface_where = [];
                    $upface_where['device_remark'] = $udata['device_remark'];
                    $upface_where['school_code'] = $value['school_code'];
                    $upface_where['numbers'] = $value['numbers'];

                    $isset = $updateFaceObj->getOne('id, status, operate_type', $upface_where);
                    $nInsert = 0;

                    if ($isset) {
                        // 需要删除的，和已经执行完毕的数据删除
                        if (($isset['status'] < 0) || ($isset['operating'] == 3)) {
                            $updateFaceObj->destroy($isset['id']);
                            $nInsert = 1;
                        }
                        // 有待下发的数据，无需理会
                    } else {
                        $nInsert = 1;
                    }

                    if ($nInsert) {
                        $data = [];
                        $data['devid'] = $udata['id'];
                        $data['device_remark'] = $udata['device_remark'];
                        $data['device_uuid'] = $udata['device_uuid'];

                        $data['create_id'] = $udata['create_id'];
                        $data['school_code'] = $udata['school_code'];
                        $data['person_face_id'] = $value['id'];

                        $data['mode'] = $value['mode'];
                        $data['name'] = $value['name'];
                        $data['numbers'] = $value['numbers'];

                        $data['gender'] = $value['gender'];
                        $data['linked'] = $value['linked'];
                        $data['area'] = $value['area'];

                        $data['imgpath'] = $value['imgpath'];
                        $data['create_time'] = time();
                        $data['operate_type'] = 1;

                        $data['operate_result'] = 1;
                        $data['response_code'] = 99;
                        $data['response_msg'] = 'New face picture';

                        $data['execute_time'] = time();
                        $data['status'] = 1;

                        array_push($dataInsert, $data);
                    }
                }

                if (count($dataInsert) > 0) {
                    $result = $updateFaceObj->insertMulti($dataInsert);
                }
            }
        } catch(\Exception $e) {
            return $this->toJson(Status::CODE_BAD_REQUEST, [], "Server Error");
        }
    }

}
